const crypto = require('crypto')
const jwt = require('jwt-simple')
const {
	loginConfig,
	tokenExp
} = require('../../utils/constants.js')

const db = uniCloud.database()

async function wxlogin(event) {
	// let data = {
	//  //  AppId: 'wx00c5442b09058a1a', //微信小程序AppId
	//  //  AppSecret: 'dc0e8a80afadb472f08d2fd97dbffeb1' //微信小程序AppSecret
	//   appid: loginConfig.AppId,
	//   secret: loginConfig.AppSecret,
	//   js_code: event.code,
	//   grant_type: 'authorization_code'
	// }

	// const res = await uniCloud.httpclient.request('https://api.weixin.qq.com/sns/jscode2session', {
	//   method: 'GET',
	//   data,
	//   dataType: 'json'
	// })

	// const success = res.status === 200 && res.data && res.data.openid
	// if (!success) {
	//   return {
	//     status: -1,
	//     msg: '微信登录失败'
	//   }
	// }

	// const {
	//   openid,
	//   //session_key 暂不需要session_key
	// } = res.data

	const {
		openid
	} = event;

	let userInfo = {
		openid
	}
	let tokenSecret = crypto.randomBytes(16).toString('hex'),
		token = jwt.encode(userInfo, tokenSecret) //使用随机密钥对用户信息加密加密

	const userInDB = await db.collection('user').where({
		openid
	}).get()

	let userUpdateResult
	if (userInDB.data && userInDB.data.length === 0) {
		userUpdateResult = await db.collection('users').add({
			...userInfo,
			tokenSecret,
			exp: Date.now() + tokenExp
		})
	} else {
		userUpdateResult = await db.collection('users').doc(userInDB.data[0]._id).set({
			...userInfo,
			tokenSecret,
			exp: Date.now() + tokenExp
		})
	}

	if (userUpdateResult.id || userUpdateResult.affectedDocs === 1) {
		return {
			status: 1,
			token,
			msg: '登录成功'
		}
	}

	return {
		status: -1,
		msg: '微信登录失败'
	}
}

exports.main = wxlogin
